#include "../weiconsole_ui_NativeUI.h"
#include <stdio.h>
#include <sys/ioctl.h>

#define CL_BLACK 0
#define CL_RED 1
#define CL_GREEN 2
#define CL_LIGHTRED 3
#define CL_BLUE 4
#define CL_PURPLE 5
#define CL_LIGHTBLUE 6
#define CL_GRAY 7
#define CL_NORMAL 8

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_setBackground
  (JNIEnv * env, jobject arg, jshort color)
{
	switch (color) {
	case CL_BLACK:
		printf("\033[40m");
		break;
	case CL_RED:
		printf("\033[41m");
		break;
	case CL_GREEN:
		printf("\033[42m");
		break;
	case CL_LIGHTRED:
		printf("\033[43m");
		break;
	case CL_BLUE:
		printf("\033[44m");
		break;
	case CL_PURPLE:
		printf("\033[45m");
		break;
	case CL_LIGHTBLUE:
		printf("\033[46m");
		break;
	case CL_GRAY:
		printf("\033[47m");
		break;
	case CL_NORMAL:
		printf("\033[0m");
		break;
	}
	fflush(stdout);
}

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_setForeground
  (JNIEnv * env, jobject arg, jshort color)
{
	switch (color) {
	case CL_BLACK:
		printf("\033[30m");
		break;
	case CL_RED:
		printf("\033[31m");
		break;
	case CL_GREEN:
		printf("\033[32m");
		break;
	case CL_LIGHTRED:
		printf("\033[33m");
		break;
	case CL_BLUE:
		printf("\033[34m");
		break;
	case CL_PURPLE:
		printf("\033[35m");
		break;
	case CL_LIGHTBLUE:
		printf("\033[36m");
		break;
	case CL_GRAY:
		printf("\033[37m");
		break;
	case CL_NORMAL:
		printf("\033[0m");
		break;
	}
	fflush(stdout);
}

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_cleanScreen
  (JNIEnv * env, jobject arg)
{
	printf("\033[1H\033[2J");
	fflush(stdout);
}

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_saveCursorPos
  (JNIEnv * env, jobject arg)
{
	printf("\033[s");
	fflush(stdout);
} 

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_restoreCursorPos
  (JNIEnv * env, jobject arg)
{
	printf("\033[u");
	fflush(stdout);
}

JNIEXPORT void JNICALL Java_weiconsole_ui_NativeUI_moveCursor
  (JNIEnv * env, jobject arg, jint x, jint y)
{
	printf("\033[%d;%dH ", y, x); 
	fflush(stdout);
}

JNIEXPORT jint JNICALL Java_weiconsole_ui_NativeUI_getScrRow
  (JNIEnv * env, jobject arg)
{
	struct winsize size;
	int input_fd = 0;

	if (ioctl (input_fd, TIOCGWINSZ, &size) == -1)
		fprintf (stderr, "cannot get terminal size\n");
	else
		return size.ws_row;

	return 0;
}

JNIEXPORT jint JNICALL Java_weiconsole_ui_NativeUI_getScrCol
  (JNIEnv * env, jobject arg)
{
	struct winsize size;
	int input_fd = 0;

	if (ioctl (input_fd, TIOCGWINSZ, &size) == -1)
		fprintf (stderr, "cannot get terminal size\n");
	else
		return size.ws_col;

	return 0;
}




